from flask_restful import Resource
from database import Database

class GetOrder(Resource):
    #TODO get order and linebooks by order id
    def get(self):
       db = Database()
       data = request.form
       orderId = data.get('orderId')
       query="select * from order where orderId=%s"
       order=db.execute_query(query,(orderId,))
       lineBooks = db.execute_query("SELECT * FROM linebook WHERE orderId = %s", (order[0],))
       listBooks_json = []
       if lineBooks:
           for linebook in lineBooks:
               print(linebook[0])
               book = db.execute_query("SELECT * FROM book WHERE bookId = %s", (linebook[3],))  # Fix here

               book_data = {
                   "bookId": book[0],
                   "categoryId": book[1],
                   "imageUrl": book[2],
                   "stackId": book[3],
                   "ownerId": book[4],
                   "condition": book[5],
                   "fee": str(book[6]),
                   "price": str(book[7]),
                   "status": book[8],
                   "LineBookStatus": linebook[2],
                   "libraryAddress": linebook[4],
                   "borrowedTill": str(linebook[5]),
                   "returnAfter": str(linebook[6]),
                   "dayToken": str(linebook[7])
               }
               listBooks_json.append(book_data)
       order_data = {
           "orderId": order[0],
           "userId": order[1],
           "dateCreated": order[2].strftime("%Y-%m-%d %H:%M:%S"),
           "status": order[3],
           "quantity": order[4],
           "class": order[5],
           "listBooks": listBooks_json  # Changed to listBooks
       }
       return order_data